<template>
  <div id="VisoPage">
    <el-container class="frame">
      <el-header height="100%">
        <VisoMainToolBar ref="refMainToolBar" />
        <SymbolDefDlg ref="symbolDefDlg" />
        <CircleArrayInputDlg ref="refCircleArrayInputDlg" />
        <RectArrayInputDlg ref="refRectArrayInputDlg" />
        <SystemSetting ref="refSystemSetting" />
        <rotateAnimateDlg ref="refRotateAnimateDlg" />
        <inflateAnimateDlg ref="refInflateAnimateDlg" />
        <pistonMotionDlg ref="refPistonMotionDlg" />
        <layerManager ref="refLayerManager" />
        <symbolUnitHighSetting ref="refSymbolUnitHighSetting" />
        <ShareFileDlg ref="refShareFileDlg" />
        <NewFileDlg ref="refNewFileDlg" />
      </el-header>
      <el-container>
        <el-container style="height:100%">
          <el-aside v-if="toolvisible" width="300px" id="toolbox-containerID" height="600px">
            <div id="toolboxDivID" height="600px">{{ toolboxTitle }}
              <div class="toolBoxScrollDiv" id="toolBoxScrollID" :height=browseHgt>
                <CollapsePanel ref="refCollapsePanel" />
              </div>
            </div>
          </el-aside>
          <el-main style="width:browseWid; height:browseHgt" id="maincontainerID">
            <ul class="clickRightMenu" id="clickRightMenu"></ul>
            <el-tabs v-model="activeCanvas" class="canvasTab" @tab-change="switchCanvas" id="canvasTabID"
              type="border-card" editable @edit="handleTabsEdit">
              <el-tab-pane :label="ele.text" :name="String(ele.name)" v-for="ele in canvasList" :key="ele.id"
                class="canvasTabContent">
                <div class="canvasTabContentDIV" id="canvasTabContentDIVID">
                  <canvas :id="ele.canvasID" :z-index="3" :width=browseWid :height=browseHgt ondragover="return false"
                    class="canvasCtl"></canvas>
                </div>
              </el-tab-pane>
            </el-tabs>
            <textarea name="textBox" id="textBox" cols="10" rows="2" class="canvasTextBox"></textarea>
          </el-main>
          <el-aside width="25px" :height="asideHeight" id="propboxID">
            <el-button @click="disPropBox(null)" size="small">
              <el-icon v-if="propvisible" style="horizontal-align: left;margin-left: 0px">
                <ArrowRightBold />
              </el-icon>
              <el-icon v-if="propvisible == false" style="horizontal-align: left;margin-left: 0px">
                <ArrowLeftBold />
              </el-icon>
            </el-button>
            <div id="propAndProjID">属性编辑
              <el-container v-if="propvisible">
                <PropStyle ref="propStyleRef" />
                <el-footer>
                  <FolderTree ref="refFolderTree" />
                </el-footer>
              </el-container>
            </div>
          </el-aside>
        </el-container>
        <el-footer>
          <CommandInput ref="commandinputRef" id="commandinputRefID" />
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex';
const store = useStore();
import { ElMessageBox } from 'element-plus'

import VisoMainToolBar from '../components/viso/VisoMainToolBar.vue'
import CollapsePanel from '../components/CollapsePanel.vue'
import PropStyle from '../components/PropStyle.vue'
import CommandInput from '../components/CommandInput.vue'

import SymbolDefDlg from '../components/SymbolDefDlg.vue'
import CircleArrayInputDlg from '../components/CircleArrayInputDlg.vue';
import RectArrayInputDlg from '../components/RectArrayInputDlg.vue'
import SystemSetting from '../components/SystemSetting.vue'
import rotateAnimateDlg from '../components/rotateAnimateDlg.vue'
import inflateAnimateDlg from '../components/InflateAnimateDlg.vue'
import pistonMotionDlg from '../components/PistonMotionDlg.vue'
import FolderTree from '../components/FolderTree.vue'
import layerManager from '../components/layerManager.vue'
import symbolUnitHighSetting from '../components/symbolUnitHighSetting.vue'
import ShareFileDlg from '../components/ShareFileDlg.vue'
import NewFileDlg from '../components/NewFileDlg.vue'

import { LGXCanvas } from '../lgxcanvas.js'
import { FileAccessSvc } from '../../script/manage/service/FileAccessSvc';
import { LocalFileSvc } from '../../script/manage/service/LocalFileSvc';

const propStyleRef = ref(null);
const commandinputRef = ref(null);

const symbolDefDlg = ref(null)
const refCircleArrayInputDlg = ref(null)
const refRectArrayInputDlg = ref(null)
const refCollapsePanel = ref(null);
const refSystemSetting = ref(null);
const refRotateAnimateDlg = ref(null)
const refInflateAnimateDlg = ref(null)
const refPistonMotionDlg = ref(null)
const toolvisible = ref(true)
const propvisible = ref(false)
const toolboxTitle = ref("")
const refFolderTree = ref(null)
const refLayerManager = ref(null)
const refSymbolUnitHighSetting = ref(null)
const refMainToolBar = ref(null)
const refShareFileDlg = ref(null)
const refNewFileDlg = ref(null)
const refPatternClassDlg = ref(null)

const browseWid = ref(180)
const browseHgt = ref(560)
const asideHeight = ref(600)
const fileMode = "viso"
var canvasWidth = 500;
var canvasHeight = 500;

const activeCanvas = ref("defaultCanvas")
const canvasList = ref([{
  name: 'defaultCanvas', text: '未命名', id: 1, canvasID: 'MainPaintCanvas', mapCtrlPtr: null,
  refFile: { uuid: '', name: '', parent: '', projectid: '', userid: '' }
}]);


// 创建 ResizeObserver 实例
const canvsContainerSizeObserver = new ResizeObserver(entries => {
  for (let entry of entries) {
    var { width, height } = entry.contentRect;
    console.log('画布容器元素尺寸变化:', width, height);
    if (width < 10 || height < 10) {
      return;
    }
    browseWid.value = width;
    browseHgt.value = height;
    entry.target.style.display = 'none';
    entry.target.offsetHeight; // 强制浏览器重新渲染
    entry.target.style.display = 'block'; // 或者 'inline'
  }
});

// 创建 ResizeObserver 实例
const canvasSizeObserver = new ResizeObserver(entries => {
  for (let entry of entries) {
    const { width, height } = entry.contentRect;
    console.log('画布元素尺寸变化:', width, height);
    entry.target.style.display = 'none';
    entry.target.offsetHeight; // 强制浏览器重新渲染
    entry.target.style.display = 'block'; // 或者 'inline'
    if (width < 10 || height < 10) {
      window.mainctl.rePaint(1);
      return;
    }
    browseWid.value = width;
    browseHgt.value = height;
    if (window.mainctl) {
      window.mainctl.resizeMap(width, height);
    }
  }
});



onMounted(() => {
  console.log("visoPage onmouted----------------");
  window.propStyleTab = propStyleRef;
  window.cmdInputDlg = commandinputRef.value;
  window.circleArrayDlg = refCircleArrayInputDlg;
  window.rectArrayDlg = refRectArrayInputDlg;
  window.symbolDefDlg = symbolDefDlg;
  window.ToolCollapsePanel = refCollapsePanel;
  window.SystemSetting = refSystemSetting;
  window.RotateAnimateDlg = refRotateAnimateDlg;
  window.InflateAnimateDlg = refInflateAnimateDlg;
  window.PistonMotionDlg = refPistonMotionDlg;
  window.toolvisible = toolvisible;
  window.disPropBoxFunc = disPropBox;
  window.refFolderTree = refFolderTree;
  window.refLayerManager = refLayerManager;
  window.refSymbolUnitHighSetting = refSymbolUnitHighSetting;
  window.refMainToolBar = refMainToolBar;
  window.refShareFileDlg = refShareFileDlg;
  window.gstore = useStore();
  window.canvasList = canvasList;
  window.refNewFileDlg = refNewFileDlg;
  window.refMainToolBar = refMainToolBar;
  window.refPatternClassDlg = refPatternClassDlg;

  // 获取元素的尺寸信息
  const containerElement = document.getElementById('canvasTabContentDIVID');
  const rect = containerElement.getBoundingClientRect();

  // 获取元素的宽度和高度
  canvasWidth = rect.width;
  canvasHeight = rect.height;

  browseWid.value = canvasWidth;
  browseHgt.value = canvasHeight;

  window.addEventListener('resize', updateScreenSize);
  let ptr = new LGXCanvas('MainPaintCanvas', window.canvasManager, store.state.symbolDefData);
  window.mainctl = ptr.mainctl;
  window.canvasList.value[0].mapCtrlPtr = ptr;

  //监听画布容器的尺寸变化
  canvsContainerSizeObserver.observe(containerElement);

  //监听画布自身尺寸变化事件
  const canvasElement = document.getElementById('MainPaintCanvas');
  canvasSizeObserver.observe(canvasElement);

  store.commit("switchWorkMode", { map: ptr.mainctl, mode: 'viso' });
  store.commit("switchOnShowToolBox", onShowToolBox);

  if (store.state.lazyOpenLocalFileInfo){
    LocalFileSvc.openLocalMemFileData(store.state.lazyOpenLocalFileInfo);
    store.commit("releaseLazyOpenLocalFile", '');
  }
  else if (store.state.curentFile && store.state.curentFile.fileMode == fileMode) {
    let uuid = store.state.curentFile.uuid;
    FileAccessSvc.open(uuid);

    let curentProjID = store.state.curentFile["projectid"];
    if (curentProjID && curentProjID.length > 1) {
      disPropBox(true);
    }
  }
  else {
    store.commit("releaseLastOpenFile", "");
  }

  window.mainctl.appendSelGraphListner(window.refMainToolBar.value);

})

const updateScreenSize = () => {
  let screenWidth = window.innerWidth;
  let screenHeight = window.innerHeight;
  console.log("screenWidth:" + screenWidth + " ,screenHeight:" + screenHeight);
}

const switchCanvas = () => {
  let tabName = activeCanvas.value;
  console.log("tabchanged:" + tabName);
  let destCanvas = null;
  canvasList.value.forEach(ele => {
    if (tabName == ele.name) {
      destCanvas = ele;
      return;
    }
  });

  if (destCanvas) {
    let destMapCtrl = destCanvas.mapCtrlPtr;
    if (!destMapCtrl) {
      let ptr = new LGXCanvas(destCanvas.canvasID, window.canvasManager, store.state.symbolDefData);
      destCanvas.mapCtrlPtr = ptr;
      window.mainctl = ptr.mainctl;

      const canvasElement = document.getElementById(destCanvas.canvasID);
      canvasSizeObserver.observe(canvasElement);
    }
    else {
      window.mainctl = destMapCtrl.mainctl;
    }
  }
  window.gstore.commit("switchActiveCanvasTab", tabName);
}

const handleTabsEdit = (targetName, action) => {
  if (action === 'add') {
    let count = canvasList.value.length;
    let id = count + 1;
    let canvasID = "paintCanvas#" + id;
    let tabName = '新建页面' + id;
    let t = { name: tabName, text: tabName, id, canvasID, mapCtrlPtr: null, refFile: { uuid: '', name: '', parent: '', projectid: '', userid: '' } };

    //let t1 = browseWid.value;
    //let t2 = browseHgt.value;

    canvasList.value.push(t);
    activeCanvas.value = tabName;
    window.gstore.commit("switchActiveCanvasTab", tabName);
  }
  else if (action === 'remove') {
    ElMessageBox.confirm('当前页面图形未保存。确认关闭?', 'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        const tabs = canvasList.value
        let activeName = activeCanvas.value
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              const nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        activeCanvas.value = activeName
        canvasList.value = tabs.filter((tab) => tab.name !== targetName)
        window.gstore.commit("switchActiveCanvasTab", activeName);
      })
      .catch(() => {
        return;
      })


  }
}

var onShowToolBox = function (flag) {
  toolvisible.value = flag;
  if (flag) {
    window.gstore.commit("switchOnShowToolBox", onShowToolBox);
  }
}

/* var distoolbox = function () {
  console.log("distoolbox");
  toolvisible.value = !toolvisible.value;
  let dis = toolvisible.value;
  let ele = document.getElementById("toolbox-containerID");
  let scrolllEld = document.getElementById("toolBoxScrollID");
  var toolboxDiv = document.getElementById("toolboxDivID");
  if (ele) {
    if (dis) {
      ele.style.width = '300px';
      toolboxTitle.value = "";
      if (scrolllEld) {
        scrolllEld.style.overflowY = 'scroll';
      }
    }
    else {
      ele.style.width = '25px';
      scrolllEld.style.overflowY = "hidden";
      toolboxTitle.value = "工具箱";
    }
  }
} */

var disPropBox = function (flag) {
  if (flag == null) {
    propvisible.value = !propvisible.value;
  }
  else {
    propvisible.value = flag;
  }
  let dis = propvisible.value;
  let ele = document.getElementById("propboxID");
  if (ele) {
    if (dis) {
      let t = window.refFolderTree.value;
      if (t) {
        t.refreshData();
      }
      window.refFolderTree = refFolderTree;

      ele.style.width = '250px';
      window.mainctl.appendSelGraphListner(window.propStyleTab.value);
    }
    else {
      ele.style.width = '25px';
      window.mainctl.removeSelGraphListner(window.propStyleTab.value);
    }
  }
}

</script>

<style>
.el-header,
.el-footer {
  background-color: #B3C0D1;
  color: #636262;
  text-align: left;
  line-height: 20px;
  padding: 0px !important;
}

.el-lgx-footer {
  background-color: #8c958c;
  color: #0d0d0d;
  text-align: left;
  line-height: 30px;
  padding: 0px !important;
}

.el-aside {
  background-color: #D3DCE6;
  color: #545353;
  text-align: center;
  line-height: 20px;
  padding: 0px !important;
}

.el-main {
  background-color: #8da3b6;
  color: #333;
  text-align: left;
  line-height: 20px;
  padding: 0px !important;
  /* overflow: auto; */
}

body>.el-container {
  margin-bottom: 0px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 840px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 700px;
}

.el-col {
  border-radius: 8px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 10px;
  min-height: 360px;
}

.clickRightMenu {
  width: 110px;
  background-color: #fff;
  font-size: 12px;
  position: absolute;
  text-align: left;
  padding: 4px 0;
  border: 4px solid #ccc;
  display: none;
  z-index: 100;
}

.clickRightMenu li {
  list-style: none;
  line-height: 20px;
  padding-left: 25px;
}

.clickRightMenu li:hover {
  background-color: #dcdcdc;
  cursor: pointer;
}

.canvasTextBox {
  float: left;
  position: absolute;
  left: 0px;
  top: 0px;
  font: '12px 隶书';
  word-break: break-all;
  white-space: pre-wrap;
  color: rgba(255, 0, 0, 1);
  background-color: rgba(0, 0, 0, 255);
  resize: auto;
  display: none;
  z-index: 1;
  text-align: center;
}

.toolBoxScrollDiv {
  overflow-y: scroll;
  height: 600px;
}

.autoscroll_item {
  overflow-y: auto;
}

.canvasTab {
  /* width:300px; */
  height: calc(100vh - 18vh);
  /* border: '3px solid rgb(107, 106, 106)'; */
  margin: 0;
  border: none;
  padding: 0px !important;
}

.canvasTabContent {
  /* position: relative; */
  height: 100%;
  /* border: '3px solid rgb(107, 106, 106)'; */
  padding: 0px !important;
  margin: 0;
  border: none;
}

.el-tabs__content {
  height: 100%;
  padding: 0px !important;
  margin: 0;
  border: none;
}

.canvasTabContentDIV {
  position: relative;
  /* 父元素设置为相对定位 */
  background-color: rgb(0, 120, 120);
  height: 100%;
  flex: 1;
  /* 使用 flex 布局让 canvasTabContentDIV 填充剩余空间 */
  overflow-x: auto;
}

.canvasCtl {
  width: 100%;
  height: 100%;
  border: 3px solid rgb(107, 106, 106);
  background-color: rgb(120, 120, 120);
}
</style>